<template>
  <div class="student-manage-container">
    <div class="header">
      <el-button type="primary" plain icon="ArrowLeft" @click="goBack" class="back-button">返回</el-button>
      <el-icon class="user-icon"><User /></el-icon>
      <span class="title">考生管理</span>
    </div>

    <div class="search-bar">
      <div class="left-filters">
        <el-dropdown trigger="click" @command="handleDepartmentChange">
          <span class="el-dropdown-link">
            <el-button type="primary" plain>
              <el-icon><OfficeBuilding /></el-icon>
              {{ selectedClass ? selectedClass.className : '所属班级' }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item 
                v-for="classInfo in classList" 
                :key="classInfo.classId" 
                :command="classInfo"
              >
                {{ classInfo.className }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-input
          v-model="searchKeyword"
          placeholder="请输入关键字查询"
          clearable
          style="width: 240px; margin-left: 10px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="searchStudent" style="margin-left: 10px;">
          <el-icon><Search /></el-icon>
        </el-button>
      </div>

      <div class="filters">
        <el-button icon="Refresh" @click="refreshList" circle></el-button>
      </div>
    </div>

    <div class="action-buttons">
      <el-button type="primary" @click="addNewStudent">
        <el-icon><Plus /></el-icon>新增考生
      </el-button>
      <el-button type="primary" @click="importStudents">
        <el-icon><Upload /></el-icon>批量导入
      </el-button>
      <el-button type="primary" @click="createClass">
        <el-icon><Plus /></el-icon>创建班级
      </el-button>

      <div class="right-actions">
        <el-dropdown trigger="click" @command="handleBatchActions">
          <el-button type="primary" plain>
            <el-icon><Operation /></el-icon>批量操作
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="activate">批量激活</el-dropdown-item>
              <el-dropdown-item command="disable">批量禁用</el-dropdown-item>
              <el-dropdown-item command="resetPwd">批量重置密码</el-dropdown-item>
              <el-dropdown-item command="moveDept">批量移动班级</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="账号" min-width="120" />
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="schoolNumber" label="学号" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="classId" label="班级ID" min-width="100" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '激活' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <div class="total-info">
          <span class="total-text">共 {{ total }} 条记录</span>
          <div class="page-size-wrapper">
            <span>每页</span>
            <el-select v-model="pageSize" class="page-size-select" @change="handleSizeChange">
              <el-option :value="10" label="10条" />
              <el-option :value="20" label="20条" />
              <el-option :value="50" label="50条" />
              <el-option :value="100" label="100条" />
            </el-select>
          </div>
        </div>

        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
          background
          class="custom-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加批量导入弹窗 -->
    <el-dialog
      v-model="importDialogVisible"
      title="考生导入"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="import-steps">
        <div class="step-title">第一步、选择班级</div>
        <div class="select-class">
          <el-select v-model="selectedClassId" placeholder="请选择班级" style="width: 100%;">
            <el-option
              v-for="classInfo in classList"
              :key="classInfo.classId"
              :label="classInfo.className"
              :value="classInfo.classId"
            />
          </el-select>
        </div>

        <div class="step-title" style="margin-top: 20px;">第二步、下载导入模板</div>
        <div class="download-template">
          <el-button type="primary" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            导入模板（点击下载）
          </el-button>
        </div>

        <div class="step-title" style="margin-top: 20px;">第三步、上传导入文件</div>
        <div class="upload-area">
          <el-upload
            class="upload-excel"
            action="#"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传文件导入账号
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传 Excel 文件（.xlsx）
              </div>
            </template>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeImportDialog">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 创建班级弹窗 -->
    <el-dialog
      v-model="createClassDialogVisible"
      title="创建班级"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="createClassForm" label-width="100px">
        <el-form-item label="班级名称">
          <el-input v-model="createClassForm.classname" placeholder="请输入班级名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCreateClassDialog">取消</el-button>
          <el-button type="primary" @click="submitCreateClass" :loading="creatingClass">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增考生弹窗 -->
    <el-dialog
      v-model="addStudentDialogVisible"
      title="新增考生"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="addStudentForm" label-width="100px" :rules="addStudentRules" ref="addStudentFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addStudentForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="addStudentForm.real_name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="school_number">
          <el-input v-model="addStudentForm.school_number" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addStudentForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="所属班级" prop="class_id">
          <el-select v-model="addStudentForm.class_id" placeholder="请选择班级" style="width: 100%;">
            <el-option
              v-for="classInfo in classList"
              :key="classInfo.classId"
              :label="classInfo.className"
              :value="classInfo.classId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddStudentDialog">取消</el-button>
          <el-button type="primary" @click="submitAddStudent" :loading="addingStudent">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 移动班级对话框 -->
    <el-dialog
      v-model="moveClassDialogVisible"
      title="移动班级"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="moveClassForm" label-width="100px">
        <el-form-item label="目标班级" required>
          <el-select v-model="moveClassForm.targetClassId" placeholder="请选择目标班级" style="width: 100%;">
            <el-option
              v-for="classInfo in classList"
              :key="classInfo.classId"
              :label="classInfo.className"
              :value="classInfo.classId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeMoveClassDialog">取消</el-button>
          <el-button type="primary" @click="submitMoveClass" :loading="movingClass">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看考生详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看考生详情"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="student-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="账号">{{ viewForm.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ viewForm.realName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ viewForm.schoolNumber }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ viewForm.email || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="所属班级">{{ viewForm.className || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(viewForm.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="viewForm.status === '激活' ? 'success' : 'danger'">
              {{ viewForm.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeViewDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  OfficeBuilding, 
  Search, 
  Plus, 
  Upload, 
  Operation, 
  View, 
  Delete,
  Refresh,
  Download,
  ArrowLeft
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUser } from '@/stores/userInfo.js'
import request from '@/utils/request'
import JSEncrypt from 'jsencrypt'

const router = useRouter()
const userStore = useUser()

// 搜索和筛选条件
const searchKeyword = ref('')
const departmentFilter = ref('all')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value) || 1
})

// 选中的学生
const selectedStudents = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 批量导入相关
const importDialogVisible = ref(false)
const uploadFile = ref(null)
const selectedClassId = ref(null)
const importing = ref(false)

// 在 script setup 部分添加班级列表数据
const classList = ref([])

// 创建班级相关
const createClassDialogVisible = ref(false)
const creatingClass = ref(false)
const createClassForm = ref({
  classname: '',
  teacherNumber: ''
})

// 新增考生相关
const addStudentDialogVisible = ref(false)
const addingStudent = ref(false)
const addStudentFormRef = ref(null)
const addStudentForm = ref({
  username: '',
  real_name: '',
  school_number: '',
  password: '',
  class_id: null,
  role: 'student'
})

// 表单验证规则
const addStudentRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  school_number: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  class_id: [
    { required: true, message: '请选择所属班级', trigger: 'change' }
  ]
}

// 在 script setup 部分添加
const selectedClass = ref(null)

// 获取学生列表
const getStudentList = async () => {
  try {
    loading.value = true
    const response = await request.get('/filterStudentsByClass', {
      params: {
        teacherNumber: userStore.userInfo.schoolNumber,
        classId: selectedClass.value ? selectedClass.value.classId : undefined,
        keyword: searchKeyword.value || undefined,
        page: currentPage.value - 1, // 后端从0开始计数
        size: pageSize.value
      },
      headers: {
        'Authorization': userStore.userInfo.token
      }
    })
    
    if (response.code === 200) {
      tableData.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取学生列表失败')
    }
  } catch (error) {
    console.error('获取学生列表失败：', error)
    ElMessage.error('获取学生列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取班级列表
const getClassList = async () => {
  try {
    const response = await request.get('/getClassByTeacherNumber', {
      params: {
        teacherNumber: userStore.userInfo.schoolNumber
      },
      headers: {
        'Authorization': userStore.userInfo.token
      }
    })
    
    if (response.code === 200) {
      // 确保返回的数据是数组且每个元素都有必要的属性
      if (Array.isArray(response.data)) {
        classList.value = response.data.filter(item => 
          item && typeof item === 'object' && 
          'classId' in item && 
          'className' in item
        )
      } else {
        classList.value = []
        ElMessage.warning('班级数据格式不正确')
      }
    } else {
      classList.value = []
      ElMessage.error(response.message || '获取班级列表失败')
    }
  } catch (error) {
    console.error('获取班级列表失败：', error)
    classList.value = []
    ElMessage.error('获取班级列表失败，请重试')
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据
  getStudentList()
  getClassList() // 获取班级列表
})

// 修改 handleDepartmentChange 函数
const handleDepartmentChange = (command) => {
  if (command === 'all') {
    selectedClass.value = null
    departmentFilter.value = 'all'
  } else {
    selectedClass.value = command
    departmentFilter.value = command.classId
  }
  getStudentList() // 重新获取学生列表
}

// 搜索考生
const searchStudent = () => {
  currentPage.value = 1
  getStudentList()
}

// 监听搜索关键字变化
watch(searchKeyword, (newVal) => {
  if (newVal === '') {
    getStudentList()
  }
})

// 刷新列表
const refreshList = () => {
  currentPage.value = 1
  getStudentList()
}

// 新增考生
const addNewStudent = async () => {
  await getClassList() // 获取班级列表
  addStudentDialogVisible.value = true
}

// 打开批量导入弹窗
const importStudents = async () => {
  await getClassList() // 获取班级列表
  importDialogVisible.value = true
}

// 关闭导入弹窗
const closeImportDialog = () => {
  importDialogVisible.value = false
  uploadFile.value = null
  selectedClassId.value = null
  classList.value = [] // 清空班级列表
}

// 下载模板
const downloadTemplate = () => {
  const link = document.createElement('a')
  link.href = '/批量插入学生模板.xlsx'
  link.download = '批量插入学生模板.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理文件选择
const handleFileChange = (file) => {
  uploadFile.value = file
}

// 处理超出文件限制
const handleExceed = (files) => {
  ElMessage.warning('只能上传一个文件')
}

// 处理批量操作
const handleBatchActions = async (command) => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请先选择需要操作的考生')
    return
  }

  try {
    if (command === 'activate') {
      const schoolNumbers = selectedStudents.value.map(student => student.schoolNumber)
      const response = await request.post('/activateStudents', 
        { schoolNumbers },
        {
          headers: {
            'Authorization': userStore.userInfo.token
          }
        }
      )
      
      if (response.code === 200) {
        ElMessage.success('批量激活成功')
        getStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '批量激活失败')
      }
      return
    }

    if (command === 'disable') {
      const schoolNumbers = selectedStudents.value.map(student => student.schoolNumber)
      const response = await request.post('/disableStudents', 
        { schoolNumbers },
        {
          headers: {
            'Authorization': userStore.userInfo.token
          }
        }
      )
      
      if (response.code === 200) {
        ElMessage.success('批量禁用成功')
        getStudentList() // 刷新列表
      } else {
        ElMessage.error(response.message || '批量禁用失败')
      }
      return
    }

    if (command === 'resetPwd') {
      ElMessageBox.prompt('请输入新密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '密码长度必须在6-20个字符之间'
      })
        .then(async ({ value: newPassword }) => {
          try {
            // 使用固定的公钥加密密码
            const publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7rYgHiByM6LUO1Z7ZD80OKWl1O16/c+D1zRrrP5rYq/YSG+ZuP7Bjx3tcOgFmKL97ifyAbdNn9RmvyqBRqMt8YlT9vYXYQ8MirWbnBulhC9Q9j2ab/sUIDd1qdDIuAxx5i7X377M/IIrMTe1HTID646kwkKr/eUMZ1EEjX/Xnk2lJxj3sSzKuQ+LPMLrFQ1LP1jM6MNB4auDkrQ2vNEoI41gMy0PEE168nYrQWGkRdbolDX5GNDragi9my+Uv4J2hvf1GYDzDFs+FLK5ceUKFkkoGRHouqxkizxNAC2GlMGkJdKp2NXmvDdYvXl8VGutHPN2TnL2c875dRBEHb81zQIDAQAB'
            const encryptedPassword = await encryptPassword(newPassword, publicKey)
            
            const schoolNumbers = selectedStudents.value.map(student => student.schoolNumber)
            const response = await request.post('/resetStudentsPassword', 
              { 
                schoolNumbers,
                newPassword: encryptedPassword
              },
              {
                headers: {
                  'Authorization': userStore.userInfo.token
                }
              }
            )
            
            if (response.code === 200) {
              ElMessage.success('批量重置密码成功')
              getStudentList() // 刷新列表
            } else {
              ElMessage.error(response.message || '批量重置密码失败')
            }
          } catch (error) {
            console.error('重置密码失败：', error)
            ElMessage.error('重置密码失败，请重试')
          }
        })
        .catch(() => {
          ElMessage.info('已取消重置密码')
        })
      return
    }

    if (command === 'moveDept') {
      if (!classList.value || classList.value.length === 0) {
        ElMessage.warning('暂无可用班级')
        return
      }
      
      // 打开移动班级对话框
      await getClassList() // 刷新班级列表
      moveClassDialogVisible.value = true
      return
    }

    // 其他批量操作的处理...
    ElMessageBox.confirm(
      `确定要对选中的 ${selectedStudents.value.length} 名考生进行${actionMap[command]}操作吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        ElMessage.success(`批量${actionMap[command]}操作已执行`)
      })
      .catch(() => {
        ElMessage.info('已取消操作')
      })
  } catch (error) {
    console.error('批量操作失败：', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 加密密码的方法
const encryptPassword = async (password, publicKey) => {
  // 这里使用和注册接口相同的加密方法
  // 假设您使用的是JSEncrypt库
  const jsencrypt = new JSEncrypt()
  jsencrypt.setPublicKey(publicKey)
  return jsencrypt.encrypt(password)
}

// 查看考生详情相关
const viewDialogVisible = ref(false)
const viewForm = ref({
  username: '',
  realName: '',
  schoolNumber: '',
  email: '',
  className: '',
  createTime: '',
  status: ''
})

// 关闭查看详情对话框
const closeViewDialog = () => {
  viewDialogVisible.value = false
}

// 查看考生详情
const handleView = async (row) => {
  try {
    // 获取学生班级信息
    const classResponse = await request.get('/getStudentClass', {
      params: { schoolNumber: row.schoolNumber },
      headers: {
        'Authorization': userStore.userInfo.token
      }
    });

    if (classResponse.code === 200) {
      viewForm.value = {
        ...row,
        className: classresponse.data.class_name || '未分配'
      };
      viewDialogVisible.value = true;
    } else {
      console.error('获取学生班级信息失败：', classresponse.message);
      viewForm.value = {
        ...row,
        className: '未分配'
      };
      viewDialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取学生班级信息失败：', error);
    viewForm.value = {
      ...row,
      className: '未分配'
    };
    viewDialogVisible.value = true;
  }
};

// 删除考生
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除考生 ${row.realName} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const response = await request.delete('/deleteStudent', {
          params: {
            schoolNumber: row.schoolNumber
          },
          headers: {
            'Authorization': userStore.userInfo.token
          }
        })
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          getStudentList() // 刷新列表
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败：', error)
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

// 处理每页显示条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getStudentList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getStudentList()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 提交导入
const submitImport = async () => {
  if (!selectedClassId.value) {
    ElMessage.warning('请选择班级')
    return
  }
  if (!uploadFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  const formData = new FormData()
  formData.append('excelFile', uploadFile.value.raw)
  formData.append('ClassId', selectedClassId.value)

  try {
    importing.value = true
    const response = await request.post('/importExcel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': userStore.userInfo.token
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('导入成功')
      closeImportDialog()
      getStudentList() // 刷新列表
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('导入失败：', error)
    ElMessage.error('导入失败，请重试')
  } finally {
    importing.value = false
  }
}

// 打开创建班级弹窗
const createClass = () => {
  createClassForm.value.teacherNumber = userStore.userInfo.schoolNumber
  createClassDialogVisible.value = true
}

// 关闭创建班级弹窗
const closeCreateClassDialog = () => {
  createClassDialogVisible.value = false
  createClassForm.value = {
    classname: '',
    teacherNumber: ''
  }
}

// 提交创建班级
const submitCreateClass = async () => {
  if (!createClassForm.value.classname) {
    ElMessage.warning('请输入班级名称')
    return
  }

  try {
    creatingClass.value = true
    const response = await request.post('/createClass', createClassForm.value, {
      headers: {
        'Authorization': userStore.userInfo.token
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('创建班级成功')
      closeCreateClassDialog()
      getClassList() // 刷新班级列表
    } else {
      ElMessage.error(response.message || '创建班级失败')
    }
  } catch (error) {
    console.error('创建班级失败：', error)
    ElMessage.error('创建班级失败，请重试')
  } finally {
    creatingClass.value = false
  }
}

// 关闭新增考生弹窗
const closeAddStudentDialog = () => {
  addStudentDialogVisible.value = false
  addStudentForm.value = {
    username: '',
    real_name: '',
    school_number: '',
    password: '',
    class_id: null,
    role: 'student'
  }
  if (addStudentFormRef.value) {
    addStudentFormRef.value.resetFields()
  }
}

// 提交新增考生
const submitAddStudent = async () => {
  if (!addStudentFormRef.value) return
  
  try {
    await addStudentFormRef.value.validate()
    addingStudent.value = true
    
    const response = await request.post('/addStudent', addStudentForm.value, {
      headers: {
        'Authorization': userStore.userInfo.token
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('新增考生成功')
      closeAddStudentDialog()
      getStudentList() // 刷新列表
    } else {
      ElMessage.error(response.message || '新增考生失败')
    }
  } catch (error) {
    console.error('新增考生失败：', error)
    ElMessage.error('新增考生失败，请重试')
  } finally {
    addingStudent.value = false
  }
}

// 添加返回方法
const goBack = () => {
  router.go(-1)
}

// 移动班级相关
const moveClassDialogVisible = ref(false)
const movingClass = ref(false)
const moveClassForm = ref({
  targetClassId: null
})

// 关闭移动班级对话框
const closeMoveClassDialog = () => {
  moveClassDialogVisible.value = false
  moveClassForm.value.targetClassId = null
}

// 提交移动班级
const submitMoveClass = async () => {
  if (!moveClassForm.value.targetClassId) {
    ElMessage.warning('请选择目标班级')
    return
  }

  try {
    movingClass.value = true
    const schoolNumbers = selectedStudents.value.map(student => student.schoolNumber)
    const response = await request.post('/moveStudentsClass', 
      { 
        schoolNumbers,
        targetClassId: moveClassForm.value.targetClassId
      },
      {
        headers: {
          'Authorization': userStore.userInfo.token
        }
      }
    )
    
    if (response.code === 200) {
      ElMessage.success('批量移动班级成功')
      closeMoveClassDialog()
      getStudentList() // 刷新列表
    } else {
      ElMessage.error(response.message || '批量移动班级失败')
    }
  } catch (error) {
    console.error('移动班级失败：', error)
    ElMessage.error('移动班级失败，请重试')
  } finally {
    movingClass.value = false
  }
}
</script>

<style scoped>
/* 添加关键帧动画 */
@keyframes slideInFromTop {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

.student-manage-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  animation: fadeIn 0.8s ease-out;
  background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  animation: slideInFromTop 0.6s ease-out;
  padding: 15px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
}

.back-button {
  margin-right: 15px;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.back-button:hover {
  transform: translateX(-3px);
  background: linear-gradient(45deg, #409EFF, #36cfc9);
  border-color: transparent;
  color: white;
}

.back-button::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 200%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: shimmer 2s infinite;
}

.user-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 8px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  flex-grow: 1;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transform-origin: top;
  animation: slideInFromTop 0.6s ease-out 0.2s backwards;
  transition: all 0.3s ease;
}

.search-bar:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.left-filters {
  display: flex;
  align-items: center;
}

.filters {
  display: flex;
  align-items: center;
  gap: 15px;
}

.action-buttons {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  animation: slideInFromTop 0.6s ease-out 0.4s backwards;
}

.right-actions {
  margin-left: auto;
}

.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  animation: slideInFromTop 0.6s ease-out 0.6s backwards;
  transition: all 0.3s ease;
}

.table-container:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

/* 表格行动画 */
.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover {
  transform: translateX(5px);
  background-color: #f0f9ff !important;
}

/* 表格操作按钮动画 */
.el-button--link {
  position: relative;
  transition: all 0.3s ease;
}

.el-button--link:hover {
  transform: translateY(-2px);
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 分页容器动画 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  animation: slideInFromTop 0.6s ease-out 0.8s backwards;
  transition: all 0.3s ease;
}

.pagination-container:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

/* 弹窗动画 */
.el-dialog {
  transform-origin: center;
  animation: fadeIn 0.3s ease-out;
}

.el-dialog__body {
  animation: slideInFromTop 0.4s ease-out;
}

/* 状态标签动画 */
.el-tag {
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 下拉菜单动画 */
.el-dropdown-menu {
  animation: fadeIn 0.2s ease-out;
}

.el-dropdown-menu__item {
  transition: all 0.3s ease;
}

.el-dropdown-menu__item:hover {
  transform: translateX(5px);
  background: linear-gradient(45deg, #f0f9ff, #e6f7ff);
}

/* 输入框动画 */
.el-input__inner {
  transition: all 0.3s ease;
}

.el-input__inner:focus {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

/* 上传区域动画 */
.upload-area {
  transition: all 0.3s ease;
}

.upload-area:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.total-info {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
  gap: 20px;
}

.total-text {
  color: #1890ff;
  font-weight: 500;
}

.page-size-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-select {
  width: 90px;
  margin: 0;
}

.page-size-select :deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
}

.custom-pagination {
  :deep(.el-pagination__total) {
    margin-right: 16px;
  }

  :deep(.el-pagination__jump) {
    margin-left: 16px;
  }
}

.custom-pagination :deep(.el-pager li) {
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin: 0 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.custom-pagination :deep(.el-pager li:hover) {
  color: #1890ff;
  border-color: #1890ff;
}

.custom-pagination :deep(.el-pager li.is-active) {
  background-color: #1890ff;
  border-color: #1890ff;
  color: #fff;
}

.custom-pagination :deep(.btn-prev),
.custom-pagination :deep(.btn-next) {
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 0;
  margin: 0 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.custom-pagination :deep(.btn-prev:hover),
.custom-pagination :deep(.btn-next:hover) {
  color: #1890ff;
  border-color: #1890ff;
}

.custom-pagination :deep(.btn-prev:disabled),
.custom-pagination :deep(.btn-next:disabled) {
  color: #c0c4cc;
  border-color: #e8e8e8;
  cursor: not-allowed;
}

.clickable-name {
  color: #409EFF;
  cursor: pointer;
}

.clickable-name:hover {
  text-decoration: underline;
}

.import-steps {
  padding: 0 20px;
}

.step-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.download-template {
  margin-bottom: 20px;
}

.upload-excel :deep(.el-upload__tip) {
  color: #909399;
  font-size: 13px;
  margin-top: 8px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.student-details {
  padding: 20px;
}

.student-details :deep(.el-descriptions__label) {
  width: 120px;
  justify-content: flex-end;
  font-weight: bold;
}

.student-details :deep(.el-descriptions__content) {
  padding: 12px 20px;
}

.student-details :deep(.el-tag) {
  margin: 0;
}
</style> 